// 车险订单文件上传
import Vue from 'vue'
import {store} from '@/store/index'
import router from '@/router/index'
import {deepCopy, formatDate} from '@/utils/tools'
import fileUpload from '@/components/ivew_components/file_upload/index.vue'

let vue:any = new Vue()

const conf = {
    label: '上传附件',
    icon: 'icon-xiazai',
    pag: 'carUpload',
    fn (conf={}){
        let orderId = router.currentRoute.query.orderId; 
        
        // 请求已上传文件列表
        store.dispatch('request', {

            url: 'get/files',
            data: {orderId}
            
        }).then(success =>{
            let mods = store.state['carFormStore']['carUploadList'];
            
            vue.$Modal.confirm({
                width: '840',
                render (h){
                    return h(fileUpload, {
                        props:{
                            mods,
                            ...conf
                        },
                        on: {
                            success:onSuccess,
                            error:onError,
                            deleteFile,
                            downloadFile(index){},
                        }
                    })
                }
            })
           
            
        })
        
        
       
    }

}

/*
** @params
        index: 编号
        modsCache: 上传组件配置(包含文件地址等数据)
        response: 上传文件请求返回(提取文件地址)
        file: 上传文件
        fileList: 文件列表
        
*/
function onSuccess({index, modsCache, response, file, fileList}){
    let orderId = router.currentRoute.query.orderId; 
    let currentMod = modsCache[index];
    let fileNumber = 0;
    
    currentMod.url = response.result.url;

    modsCache.forEach(mod =>{
        if(mod.url){
            fileNumber++
        }
    })

    // 判断是否需要添加 "车相"
    if(fileNumber > 7 && fileNumber < 18){

        modsCache.push({
            title: `车相${fileNumber - 6}`,
            url: '',
            uploadAt: '',
            uploadBy: '',
            uploadYear: '',
        })
        
    }

    /*
    ** 提交文件地址
    ** @params
            orderId: 订单ID
            title: 文件类型名称: 例如: '车相'
            uploadAt: 上传日期
            
    */
    store.dispatch('request', {
        url: 'post/files/id',
        data: {
            orderId,
            title: currentMod.title,
            uploadAt: formatDate(new Date()), 
            ...response.result
        }
    })

}


// 上传失败提示
function onError({index, modsCache, response, file, fileList}){
    vue.$Notic({
        title: '文件上传失败, 请重试'
    })
}


// 删除上传文件
function deleteFile ({index, modsCache}){
    let orderId = router.currentRoute.query.orderId; 
    let currentMod =  modsCache[index];

    store.dispatch('request', {
        url: 'delete/files/id',
        data: {
            orderId,
            url: currentMod.url,
            title: currentMod.ttile,
        }
    }).then(success =>{
        currentMod.url = '';
    })

}


export default conf